<?php

error_reporting(E_ALL & ~E_NOTICE & ~E_USER_NOTICE);
date_default_timezone_set("Europe/Helsinki");

$ONKILoggerURL="http://onki.fi/widget/logger.php?s=".microtime(true)."&d=";

Header("Cache-Control: no-cache");
$offset = 60 * 60 * 24 * 7;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() - $offset) . " GMT";
Header($ExpStr);

if ($_SERVER['HTTP_HOST'] != "onki.fi")
    $ONKILoggerURL = null;


// ONKI Mash-Up component main Javascript file for loading needed JS and CSS files
// The JavaScript loads all needed stylesheet and scripts to the browser.
// JavaScript by Jouni Tuominen, 23.7.2007; destroyed with some PHP by Kim Viljanen, 7.7.2008

header("Content-type: application/x-javascript; charset=utf-8");

$protocol = "http";
if (isset($_SERVER['HTTP_X_POUND_HTTPS']) && $_SERVER['HTTP_X_POUND_HTTPS'] == 'on')
	$protocol .= "s";
$baseurl = $protocol."://".$_SERVER['SERVER_NAME'].dirname($_SERVER['REQUEST_URI'])."/";
$onkiurl = $protocol."://onki.fi";
$onkiHttpApiUrl = $protocol."://".$_SERVER['SERVER_NAME'].dirname(dirname(dirname($_SERVER['REQUEST_URI'])));
if (substr($onkiHttpApiUrl, -1) != '/')
	$onkiHttpApiUrl .= "/";
$onkiHttpApiUrl .= "api/v2/http/repo/";

list($temp, $cacheid) = explode(".", microtime(true));

// --------------------------------------------------------------------
// JavaScript begins
// --------------------------------------------------------------------

?>
// ONKI Selector component main Javascript file for loading needed JS and CSS files
// The JavaScript loads all needed stylesheet and scripts to the browser.
// For more information: http://onki.fi
// Jouni Tuominen, 23.7.2007, 7.2.2011

var host = "<?php echo $baseurl ?>";
var ysourl = "<?php echo $onkiurl ?>";
var onkiFrontendUrl = "<?php echo $onkiHttpApiUrl ?>"; // onki frontend http get api
onkiFrontendUrl = "http://onki.fi/api/v2/http/repo/"; 

var fintoApiUrl = "://api.finto.fi/rest/v1/";
if ("https:" == document.location.protocol) {
  fintoApiUrl = 'https' + fintoApiUrl;
} else {
  fintoApiUrl = 'http' + fintoApiUrl;
}  

var accesskey = "";
var UILang;
var onkilogger = <?php echo ($ONKILoggerURL)?'"'.$ONKILoggerURL.'"':'null' ?>;

function loadOnkiScripts() {
	// Get access key and UI lang from the onki-selector.js URL 
	var scriptList = document.getElementsByTagName("script");
	
	for (var i=0; i<scriptList.length; ++i) {
		var value = scriptList[i].getAttribute("src");
		if (value && (value.match(/onki-selector.js/) || value.match(/onki.js/))) {
			if (value.indexOf("?") != -1) {
				if (value.indexOf("&") == -1) {
					if (value.indexOf("=") == -1)
						accesskey = "/key-" + value.substring(value.indexOf("?")+1);
					// get UI lang
					else if (value.indexOf("?l=") != 1)
						UILang = value.substring(value.indexOf("?l=")+3);
				}
				else {
					var temp = value.substring(value.indexOf("?")+1, value.indexOf("&")); 
					if (temp.indexOf("=") == -1)
						accesskey = "/key-" + temp;
					// get UI lang
					if (value.indexOf("&l=") != -1) {
						if (value.indexOf("&", value.indexOf("&l=")+1) != 1)
							UILang = value.substring(value.indexOf("&l=")+3);
						else
							UILang = value.substring(value.indexOf("&l=")+3, value.indexOf("&", value.indexOf("&l=")+1));
					}
				}
			}
			// desired way of including the key to the DWR calls would be to pass it as a GET parameter, though DWR does not support named parameters (the names are generated by DWR in the call execution phase)
			ysourl += accesskey;
		}
	}
	
	var headTag = document.getElementsByTagName("head")[0];
	
	var linkElement = document.createElement("link");
	linkElement.setAttribute("rel", "stylesheet");
	linkElement.setAttribute("type", "text/css");
	linkElement.setAttribute("href", host+"css/autocomplete.css");
	headTag.insertBefore(linkElement, headTag.firstChild);

	var scripts = new Array("engine.js", "OnkiBrowser.js", "ConceptCollector.js",
							"OnkiFinder.js", "OnkiSearch.js", "CreateOnki.js");
	
	for (var i=0; i < scripts.length; i++) {
		var script = scripts[i];
		var scriptElement = document.createElement("script");
		//scriptElement.setAttribute("src", host+script+"?<?php echo $cacheid ?>");
		scriptElement.setAttribute("src", host+script);
		scriptElement.setAttribute("type", "text/Javascript");
		scriptElement.setAttribute("charset", "UTF-8");
		
		headTag.insertBefore(scriptElement, headTag.firstChild);
	}
}

function addOnload(myfunc) {
	if (window.addEventListener)
		window.addEventListener("load", myfunc, false);
	else if (window.attachEvent)
		window.attachEvent("onload", myfunc);
}

var scripts = 0;

function addScriptLoaded() {
	scripts++;
	
	// if all the scripts are loaded, create the ONKI instances and generate UI components
	if (scripts == 6) {

		var scriptElement = document.createElement("script");
		var lang = "";
		if (UILang != undefined)
			lang = "&l="+UILang;

		//scriptElement.setAttribute("src", onkiFrontendUrl+"ontologies?format=json-onkiselector&callback=createOnkis"+lang);
		scriptElement.setAttribute("src", fintoApiUrl +"vocabularies?lang=fi&callback=createRestOnkis");
		scriptElement.setAttribute("type", "text/Javascript");
		scriptElement.setAttribute("charset", "UTF-8");
		
		var headTag = document.getElementsByTagName("head")[0];
		headTag.insertBefore(scriptElement, headTag.firstChild);
	}
}

/*
 * Alters the data from the ONKI Light REST response to a format understood by the onki selector.
 * @param object response contains information about the different vocabularies offered by the REST API.
 */
function createRestOnkis(response) {
  var edited = [];
  response = response.vocabularies;
  var index = 0;
  for (var ontology in response) {
    ontoObject = {};
    ontoObject['http://www.w3.org/2000/01/rdf-schema#label'] = response[ontology].title;
    ontoObject['http://www.yso.fi/onki-ns/onki/abbreviation'] = response[ontology].id;
    ontoObject['http://www.yso.fi/onki-ns/onki/backendUrl'] = 'http://light.onki.fi/' + response[ontology].id;
    ontoObject['http://www.yso.fi/onki-ns/onki/browser'] =  true;
    ontoObject['http://www.yso.fi/onki-ns/onki/uriIsUrl'] = false;
    ontoObject['http://www.yso.fi/onki-ns/onki/webservice'] = true;
    edited.push(ontoObject);
  }
  createOnkis(edited); 
}

function sortOntologies(a, b) { 
	return a['http://www.yso.fi/onki-ns/onki/abbreviation'] > b['http://www.yso.fi/onki-ns/onki/abbreviation'];
}


function createOnkis(data) {
	
	data.sort(sortOntologies);
	
	for (var i=0; i < data.length; i++) {
		
		var abbr = data[i]['http://www.yso.fi/onki-ns/onki/abbreviation'];

		var dwrUrl;
		var browserUrl;

		if (data[i]['http://www.yso.fi/onki-ns/onki/backendUrl']) {
			// to include the onki key into the url path
			//TODO: change backendUrls in Saha?
			if (data[i]['http://www.yso.fi/onki-ns/onki/backendUrl'].indexOf("http://www.yso.fi/onki") === 0)
				dwrUrl = ysourl + "/api/v1/dwr/" + data[i]['http://www.yso.fi/onki-ns/onki/abbreviation'];
			else
				dwrUrl = data[i]['http://www.yso.fi/onki-ns/onki/backendUrl'];
		}
		else if (data[i]['http://www.yso.fi/onki-ns/onki/customBrowser'])
			dwrUrl = data[i]['http://www.yso.fi/onki-ns/onki/customBrowser'] + "dwr";
			browserUrl = data[i]['http://www.yso.fi/onki-ns/onki/customBrowser'];

		var label = data[i]['http://www.w3.org/2000\/01/rdf-schema#label'];
		
		var uriIsUrl = data[i]['http://www.yso.fi/onki-ns/onki/uriIsUrl'];
		var browser = data[i]['http://www.yso.fi/onki-ns/onki/browser'];

		createOnki(abbr, browserUrl, dwrUrl, label, uriIsUrl, browser);
	}
	
	createOnki(null, null, null, null, null, true);

	initOnki();
}

// add onkiLoadScripts as window's onload event listener
addOnload(loadOnkiScripts);
